import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:image/image.dart' as img;


import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';

import 'Api.dart';

class CropAspectRatioPresetCustom implements CropAspectRatioPresetData {
  @override
  (int, int)? get data => (2, 3);

  @override
  String get name => '2x3 (customized)';
}

class FileWrapper {
  File file;
  Size size;

  FileWrapper(this.file, this.size);
}



Future<List<String>?> compressAndUploadPics(List<FileWrapper> images) async {
  final client = http.Client();
  int ONE_M= 1024*1024;
  try {
    if (images == null && images.length <= 0) {
      return [];
    }
    // Create a new multipart request
    final request = http.MultipartRequest(
        'POST', Uri.parse('${Api.PROD_BASE_URL}/api/multimedia/upload/pic'));

    // Add the images to the request
    for (var image in images) {
      final img.Image? originalImage= img.decodeImage(await image.file.readAsBytes());
      img.Image? compressedImage= originalImage;
      if(ONE_M.compareTo(originalImage?.lengthInBytes as num)<0){
        int height= originalImage!.height;
        int width= originalImage!.width;
        img.Image compressedImage = height> width ? img.copyResize(originalImage!,height: 600,maintainAspect: true)
        : img.copyResize(originalImage!,width: 600,maintainAspect: true);
        print(compressedImage.lengthInBytes);
      }

      final List<int> compressedImageBytes = img.encodeJpg(compressedImage!);
      request.files.add(await http.MultipartFile.fromBytes(
        'files', compressedImageBytes,
        filename: image.file.path.split('/').last,
      ));
    }
    // Send the request
    final response = await client.send(request);

    // Check the response status code
    if (response.statusCode == 200) {
      // Publish successful
      final responseBody = await response.stream.bytesToString();
      Map<String, dynamic> reponsMap = jsonDecode(responseBody);
      return (reponsMap['data'] as List<dynamic>)
          .map((e) => e.toString())
          .toList();
    }else{
      print(response);
    }

  } catch (e) {
    print(e);
  } finally {
    client.close();
  }
  return [];
}

Future<List<FileWrapper>> selectImage(BuildContext context) async {
  List<FileWrapper> result = [];
  Completer<List<FileWrapper>> completer = Completer();
  final pickedFile = await ImagePicker().pickImage(source: ImageSource.gallery,maxHeight: 1024,maxWidth: 1024,imageQuality: 80);
  if (pickedFile != null) {
    ui.decodeImageFromList(await pickedFile.readAsBytes(), (ui.Image image) {
      double width = image.width.toDouble();
      double height = image.height.toDouble();
      print('Width: $width, Height: $height');
      result.add(FileWrapper(File(pickedFile!.path), Size(width, height)));
      completer.complete(result);
    });
  }
  return completer.future;
}
